package com.strawcom.charmring.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.android.volley.Request.Method;
import com.google.gson.Gson;
import com.strawcom.charmring.App;
import com.strawcom.charmring.BaseActivity;
import com.strawcom.charmring.C;
import com.strawcom.charmring.R;
import com.strawcom.charmring.bean.Calories;
import com.strawcom.charmring.bean.DailySummary;
import com.strawcom.charmring.bean.Friend;
import com.strawcom.charmring.bean.UserInfo;
import com.strawcom.charmring.bean.http.BaseResponse;
import com.strawcom.charmring.bean.http.LoginResponse;
import com.strawcom.charmring.bean.http.LoginResponse.EverydayDetailResponse;
import com.strawcom.charmring.bean.http.LoginResponse.EverydaySummaryResponse;
import com.strawcom.charmring.bean.http.PostEmergencyConfigRequest;
import com.strawcom.charmring.bluetooth.RingBleController;
import com.strawcom.charmring.bluetooth.RingBleService;
import com.strawcom.charmring.util.*;
import com.strawcom.charmring.util.HttpUtil.ResponeListener;
import com.strawcom.charmring.view.CustomProgressDialog;
import com.strawcom.charmring.view.TitleView;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;
import org.litepal.crud.DataSupport;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @ClassName: LoginActivity
 * @Description:登录activity
 * @author liyongqiang
 * @date 2015-3-30 下午11:47:38
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

	private TitleView textView;
	private Button btnLogin;
	private EditText editPhone, editPwd;
	private CustomProgressDialog dialog;
	private TextView tvForgatPwd, tvSavePwd;
	private ImageView imgChk;
	private boolean checked;
	private TextView mCountryText;
	
	private static final String charm_lastlogin = "charm_lastlogin";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_login);
		super.onCreate(savedInstanceState);
		initViews();
		
		findViewById(R.id.layout_content).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				
				closeInputMethod();
			}
		});
		
//		// test 跳过登录
//		actionStart(MainActivity.class);
//		finish();
	}

	private void initViews() {
		textView = (TitleView) findViewById(R.id.title_view);
		textView.setTitleText(R.string.login_title);
		editPhone = (EditText) findViewById(R.id.edit_number);
		editPwd = (EditText) findViewById(R.id.edit_pwd);
		btnLogin = (Button) findViewById(R.id.btn_login);
		btnLogin.setOnClickListener(this);
		dialog = CustomProgressDialog.createDialog(this, false).setMessage(
				R.string.wating_login);
		tvForgatPwd = (TextView) findViewById(R.id.forgat_pwd);
		tvForgatPwd.setOnClickListener(this);
		imgChk = (ImageView) findViewById(R.id.img_chk);
		tvSavePwd = (TextView) findViewById(R.id.rember_pwd);
		imgChk.setOnClickListener(this);
		tvSavePwd.setOnClickListener(this);

		mCountryText = (TextView) findViewById(R.id.country_text);

		mCountryText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final CharSequence[] charSequences = getResources().getStringArray(R.array.country_spinner);
				AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);

				builder.setTitle("选择国家编号")
						.setIcon(R.drawable.ic_launcher)
						.setItems(charSequences, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								Toast.makeText(LoginActivity.this, charSequences[which], Toast.LENGTH_SHORT).show();
								Log.i("abc", "i" + which);
								mCountryText.setText(charSequences[which]);
							}
						}).show();
			}
		});

//		String spPhone = PreferenceUtil.readString(this, C.sp.phone);
//		if(!TextUtils.isEmpty(spPhone)) {
//			editPhone.setText(spPhone);
//		}
//		checked = PreferenceUtil.readBoolean(this, C.sp.isSavePwd);
//		if (checked) {
//			String spPwd = PreferenceUtil.readString(this, C.sp.password);
//			if(!TextUtils.isEmpty(spPwd)) {
//				editPwd.setText(spPwd);
//			}
//			imgChk.setImageResource(R.drawable.chk_select);
//		}
		
		// 用户名密码和记住密码的状态在退出登录后需求不被清除，使用[charm_lastlogin]来记录这些信息
		SharedPreferences preference = getSharedPreferences(charm_lastlogin,
				Context.MODE_PRIVATE);
		String ssPhone = preference.getString(C.sp.s_phone, "");
		checked = preference.getBoolean(C.sp.s_is_pwd_saved, true);
		String ssPassword=  preference.getString(C.sp.s_password, "");


		String countryText = preference.getString(C.sp.s_phone_ex, "");
		if (!countryText.equals("")) {
			mCountryText.setText("+"+countryText);
			System.out.println("2,"+ssPhone);
			ssPhone = ssPhone.substring(countryText.length());
			System.out.println("3,"+ssPhone);
		}

		editPhone.setText(ssPhone);
		if (checked) {
			editPwd.setText(ssPassword);
			imgChk.setImageResource(R.drawable.chk_select);
		}
	}

	private UserInfo checkRegister() {
		UserInfo userInfo = new UserInfo();
		Editable mobile = editPhone.getText();
		if (TextUtils.isEmpty(mobile)) {
			editPhone.setHint(R.string.phone_null);
			return null;
		} else {
			/*Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");*/
			Pattern p = Pattern
					.compile("^(1[3-9][0-9])\\d{8}$");
			Matcher m = p.matcher(mobile.toString());
			if (m.matches()||isOtherCountry()) {
				StringBuffer stringBuffer = new StringBuffer(mCountryText.getText());
				String countryText = stringBuffer.deleteCharAt(0).toString();
				userInfo.setPhone(countryText + mobile.toString());
			} else {
				editPhone.setText("");
				editPhone.setHint(R.string.phone_format);
				return null;
			}
		}

		Editable pwd = editPwd.getText();
		if (TextUtils.isEmpty(pwd)) {
			editPwd.setHint(R.string.pwd_null);
			return null;
		} else {
			if (editPwd.getText().toString().trim().length() < 6
					|| editPwd.getText().toString().trim().length() > 16) {
				editPwd.setText("");
				editPwd.setHint(R.string.pwd_format);
				return null;
			} else {
				String password = editPwd.getText().toString().trim();
				userInfo.setPassword(password);
			}
		}
		return userInfo;
	}

	//my mandation -- https连接
	public static InputStream requestLogin(String address, String username,
			String password, Context context) {
		String author = "Basic"
				+ Base64Code.encode((username + ":" + password).getBytes());
		
		LogUtil.d("request login :address:" + address + ",username:" + username +",password:" + password);
		InputStream ins = InputStreamProvider.getInputStream(context, address, author);
		return ins;
	}
	
	//源代码http连接
	public static InputStream requestLogin(String address, String username,
			String password) {
		LogUtil.d("request login :address:" + address + ",username:" + username +",password:" + password);
		URL url;
		HttpURLConnection conn = null;
		InputStream ins = null;
		try {
			url = new URL(address);
			conn = (HttpURLConnection) url.openConnection();
			String author = "basic "
					+ Base64Code.encode((username + ":" + password).getBytes());
			conn.setRequestProperty("Authorization", author);
			conn.connect();
			ins = conn.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
        
		return ins;
	}
	
	
	
	public void login(final UserInfo info){
		dialog.show();
		final String url= HttpUtil.url+Base64Code.encode(C.request_msgid_get_user_signin.getBytes());
		new Thread(){
			public void run() {
				InputStream is = HttpUtil.http ? requestLogin(url, info.getPhone(), info.getPassword()) : 
					requestLogin(url, info.getPhone(), info.getPassword(), LoginActivity.this);
				System.out.println("info.getPhone() = " + info.getPhone());
				int result = -1;
				if(is != null) {
					String rs=BaseUtil.inputStreamToString(is);
					result = storeLoginInfo(rs);
					System.out.println("result = " + result);
				}
				final int  requestResult  =result;
				LoginActivity.this.runOnUiThread(new Runnable() {
					@Override public void run() {
						if(dialog != null) dialog.dismiss();
						switch (requestResult) {
						case -1:
							showToast(R.string.request_error);
							break;
						case 107:
							showToast(R.string.login_params_wrong);
							break;
						case 0:
							startActivity(new Intent(LoginActivity.this, MainActivity.class));
							finish();
							break;
						
						}
					}
				});
			};
		}.start();
	}

	private int storeLoginInfo(String info) {
		if(TextUtils.isEmpty(info)) {
			return -1;
		}
		LogUtil.d("login info:" + info);
		LoginResponse loginResponse = new Gson().fromJson(info, LoginResponse.class);
		if(loginResponse.retcode != 0) {
			return loginResponse.retcode;
		}
		
		storeContactInfo(loginResponse.alarmnode_tbl);
		storeUserInfo(loginResponse.register_tbl);	
		storeExerciseInfo(loginResponse.everyday_detail_tbl, loginResponse.everyday_summary_tbl);
		storeDefaultProperties();
		
		return 0; // 0- success
	}
	
	private void storeContactInfo(PostEmergencyConfigRequest contactInfo){
		if(contactInfo == null) {
			LogUtil.e("contactInfo null");
			return;
		}
		
		PostEmergencyConfigRequest without86 = new PostEmergencyConfigRequest();
		without86.msg = contactInfo.msg;
		without86.contactlist = new ArrayList<Friend>();
		for (Friend f : contactInfo.contactlist) {
			if(f.phone != null && f.phone.length()>11){
				f.phone  = f.phone.substring(f.phone.length()-11);
			}
			without86.contactlist.add(f);
		}
		String ci = HttpUtil.gson.toJson(without86);
		PreferenceUtil.write(this, C.sp.alarm_msg_info, ci);
	}
	
	private void storeUserInfo(LoginResponse.UserResponse userResponse){
		if(userResponse == null) {
			LogUtil.e("userResponse null");
			return;
		}
		StringBuffer stringBuffer = new StringBuffer(mCountryText.getText());
		String countryText = stringBuffer.deleteCharAt(0).toString();

		PreferenceUtil.write(this, C.sp.username, userResponse.username);
		PreferenceUtil.write(this, C.sp.password, userResponse.password);
		PreferenceUtil.write(this, C.sp.phone_ex, countryText);
		String phone = userResponse.phoneno;
		PreferenceUtil.write(this, C.sp.phone, phone);
		System.out.println("1,"+phone);
		if(userResponse.birthday != null){
				//服务器返回格式是yyyyMMdd
			
			
			PreferenceUtil.write(this, C.sp.birthday, userResponse.birthday);
		}
		
		PreferenceUtil.write(this, C.sp.sex, 1 == userResponse.sex);
		PreferenceUtil.write(this, C.sp.height, userResponse.height);
		PreferenceUtil.write(this, C.sp.weight, userResponse.weight);
		PreferenceUtil.write(this, C.sp.headurl, userResponse.photourl);
		
		/** 保存不需要被清空的登录账户密码 */
		PreferenceHelper.write(this, charm_lastlogin, C.sp.s_phone, phone);
		PreferenceHelper.write(this, charm_lastlogin, C.sp.s_password, userResponse.password);
		PreferenceHelper.write(this, charm_lastlogin, C.sp.s_is_pwd_saved, checked);
		PreferenceHelper.write(this, charm_lastlogin, C.sp.s_phone_ex,countryText);
		
		// 重新上传 ?????
		String servsion = "1.00"; // ring
		String hversion = "1.00"; // ring
		String appversion = SystemTool.getAppVersion(this);
		String phonedevice = android.os.Build.BRAND + " " + android.os.Build.MODEL;
		String phoneversion = "Android " + SystemTool.getSystemVersion();
		String ringid = RingBleService.sBleAdress == null ? "123456" : RingBleService.sBleAdress;
		if(!servsion.equals(userResponse.sversion)
				||!hversion.equals(userResponse.hversion)
				||!appversion.equals(userResponse.appversion)
				||!phonedevice.equals(userResponse.phonedevice)
				||!phoneversion.equals(userResponse.phoneversion)){
			// 重新上传
			UserInfo info = new UserInfo();
			info.setUsername(userResponse.username);
			info.setPassword(userResponse.password);
			info.setPhone(userResponse.phoneno);
			info.setBirthday(userResponse.birthday);
			info.setHeight(userResponse.height);
			info.setWeight(userResponse.weight);
			info.setSex(userResponse.sex);
			LogUtil.e("重新上传的用户sex:" + userResponse.sex);
			info.setSversion(servsion);
			info.setHversion(hversion);
			info.setAppversion(appversion);
			info.setPhonedevice(phonedevice);
			info.setPhoneversion(phoneversion);
			info.setRingid(ringid);
			updateInfo(info);
		}
	}
	
	private void updateInfo(UserInfo info) {
		info.msgid = C.request_msgid_post_user_change_info;
		dialog.show();
		HttpUtil.requestJson(Method.POST, info, new ResponeListener() {
			@Override
			public void onResponse(BaseResponse response,String resultStr) {
				dialog.dismiss();
			}

			@Override
			public void onErrorResponse(Exception error) {
				dialog.dismiss();
			}
		});
	}
	/** store exercise info to database */
	private void storeExerciseInfo(List<LoginResponse.EverydayDetailResponse>
			everydayDetailResponseList, List<LoginResponse.EverydaySummaryResponse> everydaySummaryResponseList){
		
		if(everydaySummaryResponseList == null || everydaySummaryResponseList.size() < 1) {
			LogUtil.e("everydaySummaryResponseList empty !!!!!"); // 这个是根本，　不能为空
			DataSupport.deleteAll(DailySummary.class); //清除原数据
			App.i().getDailySummary(true);
			return;
		}
		
		DataSupport.deleteAll(DailySummary.class); //清除原数据
		for (EverydaySummaryResponse esr : everydaySummaryResponseList) {
			DailySummary dailySummary = new DailySummary();
			dailySummary.setDate(esr.date);
			dailySummary.setWeight(esr.weight);
			dailySummary.setSyncflag1(!App.i().today.equals(esr.date));
			dailySummary.setSyncflag2(!App.i().today.equals(esr.date));
			dailySummary.setTargetTime(esr.tgttime);
			dailySummary.setTargetEnergy(esr.tgtcalorie);
			dailySummary.save();
		}
		App.i().getDailySummary(true); // init today
		
		if(everydayDetailResponseList == null || everydayDetailResponseList.size() < 1) {
			LogUtil.e("everydayDetailResponseList empty !!!!!");
			return;
		}
		
		for (EverydayDetailResponse edr : everydayDetailResponseList) {
			if(edr.exercises != null) {
				if(edr.date == null) continue;
				
				List<DailySummary>  dailySummaryList= DataSupport.where("date == ?" ,edr.date).find(DailySummary.class);
				DailySummary ds;
				if(dailySummaryList == null || dailySummaryList.size() < 1){
					ds = DailySummary.newIntance(LoginActivity.this,edr.date );
				}else{
					ds = dailySummaryList.get(0) ;
				}
				
				long t2000ToToday = FormatUtil.parseDate(ds.getDate(), FormatUtil.yyyyMMdd).getTime() / 1000 
					- RingBleController.offsetTime;
				// 由于是东八区 ，需要加上8个小时
				t2000ToToday = t2000ToToday + 8 * 3600; // [秒]
				
				for (EverydayDetailResponse.Exercises e : edr.exercises) {
					Calories calories = new Calories();
					
					calories.setType(e.type);
					calories.setDistance(e.distance);
					Date start = FormatUtil.parseDate(e.starttm, FormatUtil.HHmmss);
					Date end = FormatUtil.parseDate(e.endtm, FormatUtil.HHmmss);
					
					calories.setRecordTime(start.getTime() / 1000 + t2000ToToday);
					
					calories.setRecordTimeInfo(FormatUtil.formatDate(start, FormatUtil.HH_mm));
					calories.setDuration((int)((end.getTime() - start.getTime()) / 60000));
					calories.setCalorie(e.calorie);
					calories.setStep(e.samplecnt);
					calories.setDailySummary(ds );
					calories.save();
				}
			}
		}
	}
	
	private void storeDefaultProperties(){
		PreferenceUtil.write(this, C.sp.switch_phone_calls_reminding, true);
		PreferenceUtil.write(this, C.sp.switch_location_alarm, true);
		PreferenceUtil.write(this, C.sp.switch_mobile_lost_proof, true);
		PreferenceUtil.write(this, C.sp.switch_phone_calls_reminding, true);
		PreferenceUtil.write(this, C.sp.switch_light_open, true);
		PreferenceUtil.write(this, C.sp.switch_light_time, C.app.default_ble_light_time);
	}


	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_login:
			UserInfo info = checkRegister();
			if (info != null) {
				login(info);
			}
			break;
		case R.id.forgat_pwd:
			startActivity(new Intent(this, ResetPwdActivity.class));
			break;
		case R.id.img_chk:
		case R.id.rember_pwd:
			checked = !checked;
			PreferenceUtil.write(this, C.sp.isSavePwd, checked);
			if (checked) {
				imgChk.setImageResource(R.drawable.chk_select);
			} else {
				imgChk.setImageResource(R.drawable.chk_normal);
			}
			break;
		}
	}
	private boolean isOtherCountry() {
		return !mCountryText.getText().equals("+86");
	}
}
